/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package acscoreserver;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.persistence.Query;



import javax.persistence.Persistence;
import javax.persistence.EntityManagerFactory;


/**
 *
 * @author Ricardo
 */
public class SendMail extends Thread {

    
    String sendtoquecmd;

    public SendMail(String sendtoquecmd){
        this.sendtoquecmd=sendtoquecmd;

    }


    @Override
    public void run () {
        

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("acscoreserverPU");
            //EntityManager em = emf.createEntityManager();
        //entityManager1= emf.createEntityManager();

        javax.persistence.EntityManager entityManager1 = java.beans.Beans.isDesignTime() ? null : emf.createEntityManager();
        //javax.persistence.EntityManager entityManager1 = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("acscoreserverPU").createEntityManager();
        Query q= entityManager1.createNativeQuery("SELECT id, nome, mail, telemovel FROM mails");



        List l=q.getResultList();

        Iterator it = l.iterator();

        InternetAddress[] ia = new InternetAddress[l.size()];

        int i=0;

        while(it.hasNext()){

            Vector ob=(Vector) it.next();

            try {
                ia[i] = new InternetAddress(ob.get(2).toString(), ob.get(1).toString());
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
                System.err.println("\n\nSendMail.java:82:UnsupportedEncodingException: "+ex.getMessage());
            }

            //System.out.println("HHHHHHHHHHH "+ob.get(1).toString()+" HHHHHHHHHHHHHHHHHHH"+ob.get(1).toString());
            i++;
        }



        try
        {

            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            Properties prop = new Properties();





            //prop.put("mail.transport.protocol", "smtp");
            prop.put("mail.smtp.host", "mail.barreiras.com.pt");
            //prop.put("mail.smtp.auth ", "true");
            
            //prop.put("mail.smtp.port", "465");
            //prop.put("mail.smtp.ssl.enable","true");

            //prop.put("mail.smtp.auth", "true");
            //prop.put("mail.debug", "true");
            //prop.put("mail.smtp.socketFactory.port", "465");
            //prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            //prop.put("mail.smtp.socketFactory.fallback", "false");



            //prop.put("mail.smtp.starttls.enable","true");
            prop.put("mail.smtp.auth", "true");  // If you need to authenticate
            // Use the following if you need SSL
            //prop.put("mail.smtp.socketFactory.port", "465");
            //prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            //prop.put("mail.smtp.socketFactory.fallback", "false");



            

            Session session = Session.getDefaultInstance(prop,new ForcedAuthenticator());
            //session.setDebug(true);

            MimeMessage msg = new MimeMessage(session);

            InternetAddress addressFrom = new InternetAddress("Barreiras ACS<acs@barreiras.com.pt>");
            msg.setFrom(addressFrom);

            InternetAddress addressTo = new InternetAddress("acs@barreiras.com.pt");
            msg.setRecipient(Message.RecipientType.TO,addressTo);
            msg.setRecipients(Message.RecipientType.BCC,ia);

            Date dt= new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
            String s = formatter.format(dt);



            msg.setSubject("[ACSERVER "+s+" ] Um jogador ligou-se ao servidor barreirasac.servegame.com");
            msg.addHeader("HEADER", "Razi header ");

            String smail="<html> <table  cellpadding=\"10\" cellspacing=\"5\" ><tbody><tr><td style=\"background-color: rgb(29, 31, 29);\"> <br> <img style=\"width: 193px; height: 81px;\" alt=\"\"  src=\"http://assault.cubers.net/imgs/headerLogo.png\"><font  style=\"text-align: center; background-color: rgb(230, 230, 230);\"><br> <span style=\"font-family: Arial;\">&nbsp;Junta-te ao jogo no servidor barreirasac.servegame.com&nbsp;</span> </font> <br> <br> <font  style=\"text-align: center; background-color: rgb(230, 230, 230);\"><br> <span style=\"font-family: Arial;\">&nbsp;<small>Para mais informações visita <a href=\"http://acs.barreiras.com.pt\">http://acs.barreiras.com.pt</a>&nbsp;</small></span> </font><br> <br> </td></tr></tbody></html> ";
            msg.setContent(smail, "text/html");

            //Transport.send(msg);
            Transport.send(msg, ia);





        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("\n\nSendMail.java:144:Exception: "+e.getMessage());
        }






        //enviar toques
        it = l.iterator();
        while(it.hasNext()){

            Vector ob=(Vector) it.next();
            if(sendtoquecmd.length()>10){
                if(ob.get(3)!=null){
                    if(ob.get(3).toString().length()==9){
                        Process p;
                        try {
                            System.out.println("\n\n"+sendtoquecmd.replace("<num>",ob.get(3).toString())  );
                            p = Runtime.getRuntime().exec( sendtoquecmd.replace("<num>",ob.get(3).toString()) );
                            p.waitFor();
                        } catch (IOException ex) {
                            System.out.println("\n\nSendMail.java:70:IOException: "+ex.getMessage());
                        }
                        catch (InterruptedException ex) {
                            System.out.println("\n\nSendMail.java:73:InterruptedException: "+ex.getMessage());
                        }
                    }
                }
            }
        }




        



        //entityManager1.clear();
        entityManager1.close();
        emf.close();

        

    }



  class ForcedAuthenticator extends Authenticator {
        @Override
    public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("acs@barreiras.com.pt","serverb");
    }
  }

}
